package com.ch.web.service.impl;

import com.ch.web.redis.EmailCache;
import com.ch.web.service.EmailService;
import com.ch.web.utils.R;
import com.ch.web.vo.EmailCacheVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    EmailCache emailCache;
    private static final Executor executor = Executors.newCachedThreadPool();

    @Override
    public R sendCode(final String email) {
        executor.execute(() -> {
            try {
                MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
                //邮件发送人
                mimeMessageHelper.setFrom("1429542285@qq.com");
                //邮件接收人
                mimeMessageHelper.setTo("1429542285@qq.com");
                //邮件主题
                mimeMessageHelper.setSubject("小浩科技:");
                String random = RandomStringUtils.random(6, false, true);
                String content = "<html>\n" +
                        "<body>\n" +
                        "    <h1>您好,你注册的账号的验证码是" + random + "</h1>\n" +
                        "</body>\n" +
                        "</html>";
                mimeMessageHelper.setText(content, true);
                emailCache.addEmailCode(email, new EmailCacheVo(Integer.parseInt(random), new Date()));
                javaMailSender.send(mimeMailMessage);
            } catch (Exception e) {
                log.error("邮件发送失败{}", e.getMessage());
            }
        });
        return R.ok();
    }


}
